import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:honeypotflutter/modules/billing/views/billing_item.dart';
import 'package:honeypotflutter/public/public_date.dart';
import 'package:honeypotflutter/public/views/public_refresh.dart';
import '../../api/billingApi.dart';
import '../../model/billing_list.dart';
import '../../model/billing_param.dart';
import 'logic.dart';

class BillingList extends StatelessWidget {
  /// 类型
  final int? billType;

  /// 刷新
  final HLRefreshController? refreshController;

  /// tag
  final String? tag;

  BillingList({
    super.key,
    this.billType,
    this.refreshController,
    this.tag,
  });

  final BillingLogic _logic = Get.find<BillingLogic>();

  late final BillingParam _param = BillingParam(BillType: billType);

  /// 时间列表
  final List<String> _dataList = [];
  /*
  * 是否包含时间
  * */
  String? containDate(String? date) {
    if (date == null || date.isEmpty) {
      return null;
    }
    String newDate = HLDate.hl_format(date: date, type: DateType.YYMMDD);
    if (_dataList.contains(newDate)) {
      return null;
    }
    _dataList.add(newDate);
    return newDate;
  }

  /*
  * 网络请求
  * */
  Future<List<BillingListModel>> request(bool isRefresh) async {
    if (isRefresh) {
      _param.page = 1;
    } else {
      _param.page += 1;
    }
    _param.startTime = _logic.startTime;
    _param.endTime = _logic.endTime;

    try {
      List<BillingListModel> result = await BillingApi.billingList(_param);
      if (result.isEmpty) {
        return result;
      }
      List<BillingListModel> newResult = result.map((e) {
        e.showDate = containDate(e.createTime);
        return e;
      }).toList();
      return newResult;
    } catch (error) {
      return Future.error(error);
    }
  }

  @override
  Widget build(BuildContext context) {
    return HLRefresh<BillingListModel>(
      padding: EdgeInsets.only(top: 10),
      tag: tag,
      refreshController: refreshController,
      showSeparated: false,
      onRefresh: () async {
        _dataList.clear();
        return await request(true);
      },
      onLoading: () async {
        return await request(false);
      },
      snap: (v, int index) {
        return BillingItem(itemModel: v);
      },
    );
  }
}
